<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="租户用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="租户用户名"
          clearable
          @clear="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="租户邮箱" prop="email" label-width="130px">
        <el-input
          v-model="queryParams.email"
          placeholder="租户邮箱"
          clearable
          @clear="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="租户手机号" prop="phonenumber" label-width="130px">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="租户手机号"
          clearable
          @clear="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['tenant:tenantUser:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tenant:tenantUser:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tenant:tenantUser:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5" v-show="true">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['tenant:tenantUser:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="listTenantUser" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="110" align="center" />
      <el-table-column label="租户用户名" width="140" align="center" prop="userName" />
      <el-table-column label="租户邮箱" width="180" align="center" prop="email" />
      <el-table-column label="租户手机号" width="110" align="center" prop="phonenumber" />
      <el-table-column label="性别" width="110" align="center" :formatter="sexFormat"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column width="110" label="状态" align="center" :formatter="statusFormat"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['tenant:tenantUser:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tenant:tenantUser:remove']"
          >删除</el-button>
          <el-button
            v-if = "scope.row.status != 2"
            size="mini"
            type="text"
            icon="el-icon-stopwatch"
            @click="handleStatus(scope.row)"
            v-hasPermi="['tenant:tenantUser:updateTenantUserStatus']"
          >
            <span v-if="scope.row.status == 0">停用</span>
            <span v-if="scope.row.status == 1">正常</span>
          </el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['auth:user:resetPwd', 'auth:user:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleResetPwd" icon="el-icon-key"
                                v-hasPermi="['tenant:tenantUser:resetPwd']">重置密码</el-dropdown-item>
              <el-dropdown-item command="handleAuthRole" icon="el-icon-circle-check"
                                v-hasPermi="['tenant:tenantUser:edit']">分配角色</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改租户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名" :disabled="operationType"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type = "password" v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-top: -50px">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTenantUser, addTenantUser, delTenantUser, getTenantUser, updateTenantUser, updateTenantUserStatus} from "@/api/tenant/tenantUser/tenantUser";
import {resetUserPwd} from "@/api/auth/user";

export default {
  name: "TenantUser",
  dicts: ['sys_user_sex'],
  data() {
    return {
      operationType: true,
      // 遮罩层
      loading: true,
      // 选中数组
      userIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //获取的目录列表
      listTenantUser:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询模板列表 */
    getList() {
      this.loading = true;
      listTenantUser(this.queryParams).then(response => {
        this.listTenantUser = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //table表格格式化
    sexFormat(row, index){
      if (row.sex == 0) {
        return "男";
      } else if(row.sex == 1){
        return "女";
      }else{
        return "未知"
      }
    },
    statusFormat(row, index) {
      if (row.status == 0) {
        return "正常";
      } else if (row.status == 1) {
        return "停用";
      } else {
        return "未激活"
      }
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 分配角色操作 */
    handleAuthRole: function(row) {
      const userId = row.userId;
      const status = row.status;
      if(status == "2"){
        this.$modal.notifyWarning("该账号暂未激活，无法分配权限！");
        return;
      }
      this.$router.push("/tenant/user-auth/role/" + userId);
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
      }).then(({ value }) => {
        resetUserPwd(row.userId, value).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => {});
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.userIds = selection.map(item => item.userId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加租户";
      this.operationType = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.operationType = true;
      this.reset();
      this.open = true;
      this.title = "修改租户";
      const userId = row.userId || this.userIds
      getTenantUser(userId).then(response => {
        this.form = response.data;
        this.form.password ='';
        this.open = true;
        this.title = "修改菜单";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId == undefined) {
            addTenantUser(this.form).then(response => {
              this.$modal.msgSuccess("添加成功");
              this.open = false;
              this.getList();
            });
          }else {
            updateTenantUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      })
    },
    handleStatus(row){
      let data = {
        "userId": row.userId,
        "status": row.status,
        "userName": row.userName
      };
      //设置0和1
      if(row.status == 0){
        data.status = 1;
      }else{
        data.status = 0;
      }
      this.$modal.confirm('是否修改编号为"' + row.userId + '"租户状态').then(function() {
        return updateTenantUserStatus(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.userIds;
      this.$modal.confirm('是否确认删除租户编号为"' + userIds + '"的数据项？').then(function() {
        return delTenantUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('auth/post/export', {
        ...this.queryParams
      }, `post_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
